import os

from django.conf import settings
from django import http
from django.shortcuts import render
from django.views import View

from alipay import AliPay

from apps.orders.models import OrderInfo
from apps.payment.models import Payment
from meiduo_mall.utils.views import LoginRequiredJSONMixin


class PaymentStatusView(View):
    def get(self, request):
        # 2.接收 支付宝返回的参数 ---查询参数
        params = request.GET  # queryDict
        data_dict = params.dict()  # queryDict - -dict() ==> dict

        # 剔除 sign
        signature = data_dict.pop('sign')

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,

            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),

            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 3.让支付宝 校验参数的准确性
        success = alipay.verify(data_dict, signature)

        if success:
            # 校验通过
            # 4.存入 数据表
            Payment.objects.create(
                order=data_dict.get('out_trade_no'),
                trade_id=data_dict.get('trade_no'),
            )
            # 5. 更改订单状态 为待评价
            OrderInfo.objects.filter(
                pk=data_dict.get('out_trade_no'),
                status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']
            ).update(
                status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
            )
            return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'trade_id': data_dict.get('trade_no')})
        # 6.返回响应
        else:
            return http.JsonResponse({'code': 400, 'errmsg': '非法交易'})


class PaymentView(LoginRequiredJSONMixin, View):
    def get(self, request, order_id):

        try:
            order = OrderInfo.objects.get(user=request.user, pk=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception as e:
            return http.JsonResponse({'code': 0, 'errmsg': '订单不存在!'})

        # 1.导包
        # 2.实例化 --传必传的参数
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,

            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem'),

            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 3.调用函数 order_string = api_alipay_trade_page_pay()
        order_string = alipay.api_alipay_trade_page_pay(
            subject="美多商城",
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL
        )

        # 支付链接 https://openapi.alipaydev.com/gateway.do + ? + '加过密的参数' api_alipay_trade_page_pay()
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        # 4.返回链接
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'alipay_url': alipay_url})
